<template>
  <layout-card
    v-model="search"
    :filters="mapOptions"
    headline="信息列表"
    headtitle="数据筛选"
    :hasButton="true"
    @search-change="getData"
    @search-reset="searchReset"
  >
    <template #action>
      <el-button type="primary" @click="handleCreate('threshold')">数量阈值</el-button>
      <el-button type="primary" @click="handleCreate('export')">导出</el-button>
      <el-button type="primary" @click="handleCreate('download')">模版下载</el-button>
      <el-button type="primary" @click="handleCreate('import')">导入</el-button>
      <el-button type="primary" @click="handleCreate('add')">新增设备</el-button>
    </template>
    <table-common
      :columns="mapListColumns"
      :loading="loading"
      :pagination="pager"
      :table-data="data?.data?.list"
      size="large"
      @current-change="changeCurrent"
      @size-change="changePageSize"
    >
      <template #action="{row}">
        <!-- 自定义操作栏示例  -->
        <el-button class="link-btn" @click="handleEdit(row)" link type="primary">编辑</el-button>
        <el-button class="link-btn" link type="danger">删除</el-button>
      </template>
    </table-common>
  </layout-card>
  <edit-dialog
    :centerDialogVisible="thresholdDialogVisible"
    :tilte="addTilte"
    :key="timer"
    :defaultButton="false"
    :width=500
  >
    <template #content>
      <el-table :data="thresholdData" :pagination="false" height="200px" @row-click="hiddenMe">
        <template v-for="(item,colIndex) in thresholdListColumns" :key="colIndex">
          <el-table-column :label="item.label" :prop="item.prop" :width="item.width" align="center">
          <template #default="scope">
            <el-input-number
              v-if="isEdit && scope.$index === rowInd && scope.cellIndex === colInd"
              v-model="scope.row[item.prop]"
              size="small"
              style="width: 80px"
              controls-position="right"
              @click.stop=""
            />
            <el-select
              v-else-if="isSelect && scope.$index === rowInd && scope.cellIndex === colInd"
              v-model="scope.row[item.prop]"
              size="small"
            >
              <el-option key="1" label="是" value="是" />
              <el-option key="2" label="否" value="否" />
            </el-select>
            <div v-else @click="cellClick(scope)" style="width: 50px; height: 24px">{{scope.row[item.prop]}}</div>
          </template>
          </el-table-column>
        </template>
      </el-table>
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button @click="Cancel('threshold')">取消</el-button>
        <el-button type="primary" @click="Submit">保存</el-button>
      </span>
    </template>
  </edit-dialog>
  <edit-dialog
    :centerDialogVisible="showMapDialogVisible"
    :tilte="addTilte"
    :key="timer"
    class="showMap"
    :defaultButton="false"
    :width=1000
  >
    <template #content>
      <div style="width: 100%; height: 500px; border: 1px solid #000">地图占位</div>
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button @click="Cancel">取消</el-button>
        <el-button type="primary" @click="next">下一步</el-button>
        <el-button type="primary" @click="jump" style="background-color: #FFF; color: #2F7DF1">跳过</el-button>
      </span>
    </template>
  </edit-dialog>
  <edit-dialog
    :centerDialogVisible="addEquipmentDialogVisible"
    :tilte="addTilte"
    :key="timer"
    :defaultButton="false"
    :width=950
  >
    <template #content>
      <!-- 直接调用FilterBar组件，不再使用layoutcard组件 -->
      <FilterBar
        ref="FilterRef"
        :close-collapse="true"
        :filters="addEquipmentOptions"
        :hasButton="false"
        :hasTableButton="hasTableButton"
        :rules="rules"
        @search-change="onSearch"
        @search-reset="onReset"
        @on-toggle="(val: any)=>$emit('on-toggle',val)"
      />
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button @click="Cancel">取消</el-button>
        <el-button @click="back">返回</el-button>
        <el-button type="primary" @click="Submit">保存</el-button>
      </span>
    </template>
  </edit-dialog>
</template>

<script lang="ts" setup>
import FilterBar from '@/components/FilterBar/index.vue'
import { computed, ref, reactive, onBeforeMount } from 'vue'
import LayoutCard from '@/components/LayoutCard/index.vue'
import TableCommon from '@/components/TableCommon/index.vue'
import editDialog from '@/components/editDialog/index.vue'
import { mapListColumns, thresholdListColumns } from '@/views/Demo/config/columns'
import { mapOptions, addEquipmentOptions } from '@/views/Demo/config/filters'
import { usePagination } from 'vue-request'

const thresholdDialogVisible = ref(false)
const addEquipmentDialogVisible = ref(false)
const showMapDialogVisible = ref(false)

const isEdit = ref(false);
const isSelect = ref(false);
const rowInd = ref(0);
const colInd = ref(0);
const timer = ref()
const addTilte = ref('')
const test = ref()
// 7-27新增用于接收弹窗组件值的ref对象
const FilterRef = ref()

// 记得让columns.ts里面的对应thresholdListColumns的字段名和后端数据保持一致
const thresholdData = ref([
  { id: '1', area: '区域A', historicalAverage: '13', isAlarm: '否', setThreshold: '/' },
  { id: '2', area: '区域B', historicalAverage: '30', isAlarm: '是', setThreshold: '13' },
  { id: '3', area: '区域C', historicalAverage: '23', isAlarm: '否', setThreshold: '22' },
  { id: '4', area: '区域D', historicalAverage: '15', isAlarm: '是', setThreshold: '' },
  { id: '5', area: '区域E', historicalAverage: '27', isAlarm: '否', setThreshold: '' },
  { id: '6', area: '区域F', historicalAverage: '18', isAlarm: '是', setThreshold: '' },
])
const handleCreate = (val) => {
  Cancel()
  console.log(val)
  timer.value = new Date().getTime()
  if(val === 'threshold'){
    // 弹窗标题
    addTilte.value = "设置维护提醒"
    thresholdDialogVisible.value = true
  }else if(val === 'export'){
    console.log("导出操作")
  }else if(val === 'download'){
    console.log("下载操作")
  }else if(val === 'import'){
    console.log("导入操作")
  }else{
    // 弹窗标题
    addTilte.value = "新增设施设备"
    showMapDialogVisible.value = true
  }
}

const Cancel = () => {
  thresholdDialogVisible.value = false
  showMapDialogVisible.value = false
  addEquipmentDialogVisible.value = false
}
const back = (val) => {
  showMapDialogVisible.value = true
  addEquipmentDialogVisible.value = false
}
const jump = (val) => {
  showMapDialogVisible.value = false
  addEquipmentDialogVisible.value = true
}
const next = (val) => {
  showMapDialogVisible.value = false
  addEquipmentDialogVisible.value = true
  // 以下数据都是直接写的，需要改为从接口中获取数据
  addEquipmentOptions.forEach(e=>{
    if(e.prop == "useDepartment"){
      e.inputProps.data = [
        { // 此处的value、id值是随意定的，应该以实际数据为准
          id: 1,
          label: '全部',
          value: '0',
          children: [
            {
              id: 11,
              label: '机场股份公司',
              value: '0-1',
              children: [
                {
                  id: 111,
                  label: '航站区管理部',
                  value: '0-1-1',
                  children: [
                    { id: 1111, label: 'Toc', value: '0-1-1-1' },
                    { id: 1112, label: '楼宇管理科', value: '0-1-1-2' },
                    { id: 1113, label: '服务管理科', value: '0-1-1-3' },
                    { id: 1114, label: '安全质量科', value: '0-1-1-4' },
                    { id: 1115, label: '电力站', value: '0-1-1-5' },
                    { id: 1116, label: '空调水暖站', value: '0-1-1-6' },
                    { id: 1117, label: '综合办公室', value: '0-1-1-7' },
                    { id: 1118, label: '资产技术科', value: '0-1-1-8' }
                  ],
                },
              ],
            }
          ],
        }
      ]
    }
    if(e.prop == "subsidiary"){
      e.inputProps.options = [
        { label: '全部 24', value: 1 },
        { label: '值机、客票类 9', value: 2 },
        { label: '安检类 10', value: 3 }
      ]
    }
  })
}
// 验证规则
const rules = reactive({
  deviceID: [
    { required: true, message: '请输入设备编号', trigger: 'blur' }
  ],
  deviceType: [
    { required: true, message: '请输入设备类型', trigger: 'blur' }
  ],
  deviceName: [
    { required: true, message: '请输入设备名称', trigger: 'blur' }
  ],
  subsidiary: [
    { required: true, message: '请输入归属单位', trigger: 'blur' }
  ]
})

const Service = (data: ListParams) => {
  return new Promise((resolve) => {

    mapOptions.forEach(e=>{
      if(e.prop == "area"){
        // 这部分数据应该由接口获取
        // 刚进入页面和点击清空时，应把选择情况清空
        e.inputProps.options = [
          {label: '全部 4', value: 1},
          {label: '区域A 0', value: 2, alert: true},
          {label: '区域B 0', value: 3},
          {label: '区域C 2', value: 4}
        ]
        // 手动重写单选按钮点击事件
        e.events.change = function(value, evt){

        }
      }
      if(e.prop == "terminal"){
        e.inputProps.options = [
          {label: 'T3航站楼 24', value: 1},
          {label: 'T5航站楼 12', value: 2}
        ]
      }
    })

    // 模拟数据写入，实际开发使用接口数据写入
    setTimeout(() => {
      const response = {
        params: data,
        data: {
          list: [
            {
              id: '1', deviceID: 'A34', deviceType: '充电桩', deviceName: '充电桩', deviceModel: '/', useDepartment : '航站区管理部',
              subsidiary: '服务管理科', place: '值机柜台G区左侧', position: '(0.39484，193.4955)'
            },
            {
              id: '2', deviceID: 'B304944', deviceType: '充电桩', deviceName: '充电桩', deviceModel: '/', useDepartment: '航站区管理部',
              subsidiary: '楼宇管理科', place: '值机柜台G区右侧', position: '(0.39484，193.4955)'
            },
          ],
          total: 2
        }
      }
      resolve(response)
    }, 500)
  })
}
// =============模拟接口数据==END
const {
  run,
  data,
  loading,
  current,
  pageSize,
  total,
  changeCurrent,
  changePageSize
} = usePagination(Service, {
  manual: true,
  pagination: {
    currentKey: 'pageNum',
    pageSizeKey: 'pageSize',
    totalKey: 'data.total'
  }
})
const search = ref<FilterDataType>({})
const pager = computed(() => ({
  currentPage: current.value,
  pageSize: pageSize.value,
  total: total.value,
  // 7-24 手动设置了总页数
  pageCount: Math.ceil(total.value/pageSize.value)
}))
// 获取数据
const getData = () => {
  const params = {
    pageNum: current.value,
    pageSize: pageSize.value,
    condition: search.value
  }
  run(params)
}
// 单击 出现输入框
// setThreshold 和 isAlarm 的字段名和后端数据保持一致
const cellClick= (val: any) => {
  console.log(val.column.property,val.$index,val.cellIndex )
  if(val.column.property === "setThreshold"){
    isEdit.value = true;
    isSelect.value = false;
    rowInd.value = val.$index;
    colInd.value = val.cellIndex;
  }else if(val.column.property === "isAlarm"){
    isSelect.value = true;
    isEdit.value = false;
    rowInd.value = val.$index;
    colInd.value = val.cellIndex;
  }
};
const hiddenMe= (row, column, event) => {
  if(column != undefined){
    isEdit.value = false;
    isSelect.value = false;
  }
};
// 该功能需要完成
const Submit= (data: FilterDataType) => {
  // 通过FilterRef这个引用获取对应组件下面所有控件的值
  // FilterRef.value.getParams()
  console.log(FilterRef.value.getParams())
  //handlerUpdateModelValue(data)
  console.log(test.value)
};
const searchReset = (data: FilterDataType) => {
  search.value = data
  pager.currentPage = 1
  pager.pageSize = 10
  console.log(search.value)
  getData()
}
onBeforeMount(getData)
</script>
<style scoped>
  .showMap /deep/.el-dialog .el-dialog__body {
    padding: 0;
  }
</style>
